package com.vimtec.remote.server;

import java.awt.AWTException;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.io.IOException;

import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JMenuItem;

public class RemoteServer
{

	private static boolean running = true;
	
	private int imPort = 180;
	
	private int evPort = 181;
	
	
	private MenuItem start = null;
	
	private MenuItem stop = null;
	
	
	public RemoteServer(int imPort, int evPort) throws AWTException
	{
		this.imPort = imPort;
		this.evPort = evPort;
		createTray();
	}
	
	private void createTray() throws AWTException
	{
		ImageIcon image = new ImageIcon(getClass().getClassLoader().getResource("com/vimtec/remote/server/icon.jpg"));
		PopupMenu menu = new PopupMenu();
		start = new MenuItem("Start");
		start.addActionListener(new ServerAction(true));

		stop = new MenuItem("Stop");
		stop.addActionListener(new ServerAction(false));
		
		menu.add(start);
		menu.add(stop);
		start();
		TrayIcon icon = new TrayIcon(image.getImage(),"Remote Desktop Server",menu);
		SystemTray tray = SystemTray.getSystemTray();
		tray.add(icon);
	}
	
	public void stop()
	{
		running = false;
		start.setEnabled(true);
		stop.setEnabled(false);
	}
	
	public void start() throws AWTException
	{
		running = true;
		start.setEnabled(false);
		stop.setEnabled(true);
		Thread imageServerThread = new Thread(new DeskImageServer(imPort));
		imageServerThread.start();
		
		Thread eventServerThread = new Thread(new DeskEventsServer(evPort));
		eventServerThread.start();
		
	}
	
	public static boolean isRunning()
	{
		return running;
	}
	
	public static void main(String[] args) throws AWTException
	{
		if(args.length==2)
		{
			int imPort = Integer.parseInt(args[0]);
			int evPort = Integer.parseInt(args[1]);
			RemoteServer rs = new RemoteServer(imPort,evPort);
		}
		else
		{
			System.out.println("InCorrect Arguments");
		}
	}
	
	private class ServerAction extends AbstractAction
	{

		private boolean start;
		
		public ServerAction(boolean action)
		{
			this.start = action;
		}
		public void actionPerformed(ActionEvent arg0)
		{
			if(start)
			{
				try
				{
					start();
				} catch (AWTException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			else
			{
				stop();
			}
		}
		
		
	}
	
}
